﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Avalonia.Controls;
using Avalonia.Input;

namespace iOSClub.App.Desktop.ToolPages.Converter;

public partial class RegexConverterView : UserControl
{
    public RegexConverterView()
    {
        InitializeComponent();
    }

    private void RegexKeyUp(object? sender, KeyEventArgs e)
    {
        if (string.IsNullOrEmpty(RegexBox.Text) || string.IsNullOrEmpty(InputBox.Text)) return;
        var regex = new Regex(RegexBox.Text);
        TreeView.ItemsSource = regex.Matches(InputBox.Text).Select(x => new RegexTree(x));
    }

    private void InputKeyUp(object? sender, KeyEventArgs e)
    {
        if (string.IsNullOrEmpty(RegexBox.Text) || string.IsNullOrEmpty(InputBox.Text)) return;
        var regex = new Regex(RegexBox.Text);
        TreeView.ItemsSource = regex.Matches(InputBox.Text).Select(x => new RegexTree(x));
    }
}

public class RegexTree
{
    public List<RegexTree> Children { get; set; } = [];
    public string Name { get; set; }
    public string Value { get; set; }

    public RegexTree(Match match)
    {
        Name = match.Name;
        Value = match.Value;
        Children = match.Groups.Values.Select(x => new RegexTree(x)).ToList();
    }

    private RegexTree(Group group)
    {
        Name = group.Name;
        Value = group.Value;
    }
}